<script lang="ts" setup>
import { ref,h } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { detailApi, editApi } from '#/api/system/setting';

const key = ref('');

const [Form, formApi] = useVbenForm({
  schema: [
    {
      fieldName: 'enabled',
      label: '开启客服',
      component: 'Switch',
      componentProps: {
        class: 'w-auto',
        checkedChildren: '开启',
        checkedValue: 1,
        unCheckedChildren: '关闭',
        unCheckedValue: 0,
      },
    },
    {
      fieldName: 'provider',
      label: '在线客服方式',
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: '微信小程序客服',
            value: 'mpwxkf',
          },
          {
            label: '网页客服',
            value: 'webkf',
          },
        ],
      },
      formItemClass: 'items-start',
      wrapperClass: 'flex-wrap',
      description: () => ['小程序客服仅支持小程序端，其他端不支持', '小程序客服开启后，网页客服将失效'].map((v) => h('p', v)),
    },
    {
      fieldName: 'kflink',
      label: '客服链接',
      component: 'Input',
    },
    {
      fieldName: 'corpid',
      label: '企业ID',
      component: 'Input',
      dependencies: {
        show(values) {
            return values.provider === 'mpwxkf';
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['provider'],
      }
    },
    {
      fieldName: 'kfphone',
      label: '客服电话',
      component: 'Input',
      componentProps: {
        placeholder: '请输入客服电话',
      },
    },
    {
      fieldName: 'business',
      label: '商务合作',
      component: 'Textarea',
    },
  ],
  showDefaultActions: false,
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();
    drawerApi.lock();
    editApi(key.value, values)
      .then((res) => {
        message.success({
          content: res.message,
        });
        drawerApi.close();
      })
      .catch(() => {
        drawerApi.unlock();
      });
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData();
      formApi.resetForm();
      if (data.key) {
        key.value = data.key;
        drawerApi.setState({ title: data.describe })
        detailApi(data.key).then((res) => {
          formApi.setValues(res.values);
        })
      }
    }
  },
  overlayBlur: 1,
  title: '',
//   class: 'w-[380px]',
});
</script>
<template>
  <Drawer>
    <Form />
  </Drawer>
</template>
